#!/usr/bin/ python3
import os
import requests
from audio import headers,get_audio


def save(folder, audio):
    try:
        if not os.path.exists(folder):
            os.makedirs(folder)
        with requests.get(audio[1], headers=headers) as res:
            if res.status_code == 200:
                with open(os.path.join(folder, audio[0] + '.mp3'), 'wb') as file:
                    for chunk in res.iter_content(chunk_size=8192):
                        if chunk:
                            file.write(chunk)
    except Exception as e:
        print("{name}:下载失败:{err}".format(name=audio[0], err=e))


def download(url):
    tag = int(input('下载类型(音效:1 / 配乐：2):'))
    # url_input = input('请输入地址：')
    url_input = url
    url_base = url_input.rsplit('-', 1)[0]
    page_num = int(input('下载页数:'))
    start_page = int(input('起始页数:'))
    for p in range(page_num):
        url = url_base + '-' + str((start_page + p)) + '.html'
        print(url)
        audios = get_audio(url)
        tags = audios[1]
        audios = audios[0]
        if tag == 1:
            tag = '音效'
        elif tag == 2:
            tag = '配乐'
        for i, audio in enumerate(audios):
            save('{}/{}/{}'.format(tag, tags[0], tags[1]), audio)
            print(
                '分类：{tag1}/{tag2} / 下载页数【{page_count}】/ 当前页数【{current_page}】本页共计：{total}条：/ 当前下载第{current}条:{name}'.format(
                    tag1=tags[0], tag2=tags[1], page_count=page_num, current_page=p + 1, total=len(audios),
                    current=(i + 1),
                    name=audio[0]))
        else:
            print('下载任务结束，请到：{}查看'.format(os.path.join(tag, tags[0], tags[1])))


if __name__ == "__main__":
    download()
#  //最新下载 音效/广告设计/韵律/8
